package com.ask.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ask.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse httpServletResponse, String resourceName, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8"); //设置响应的内容类型为JSON，编码为UTF-8。
        PrintWriter writer = httpServletResponse.getWriter();

        Result error= Result.error(500, resourceName + " interface had been limited for :" + e.getMessage());
        String json = objectMapper.writeValueAsString(error); // 将响应对象转换为JSON
        writer.write(json);
        writer.flush();
    }
}
